package com.coder.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.coder.model.User;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	private String sessionName;

	private String excludeName;

	private List<String> excludeActionList;

	public List<String> getExcludeActionList(String str) {

		String[] actions = str.split(",");

		List<String> list = new ArrayList<String>();

		for (String actionName : actions) {
			list.add(actionName.trim());
		}
		return list;
	}
	
	@Override
	public void init() {
		excludeActionList = getExcludeActionList(excludeName);
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		String actionName = invocation.getProxy().getActionName();
		
		//打印请求和参数
		Map<String, Object> parameters = invocation.getInvocationContext().getParameters();
		
		System.out.print(actionName);
	    for (String key:parameters.keySet()){  
             Object obj = parameters.get(key);  
             if(obj instanceof String[]){  
                 String[] arrs = (String[]) obj;  
                 System.out.print("&"+key+"=");  
                 for (String value:arrs){  
                     System.out.print(value);  
                 }  
             }  
        }  
		System.out.println();
		
		
		if (excludeActionList.contains(actionName)) {
			// 请求的是合法
			return invocation.invoke();
		} else {
			// 查看session
			Map<String, Object> session = invocation.getInvocationContext().getSession();

			User user = (User) session.get(sessionName);

			if (user == null) {
				return "login";
			} else {
				return invocation.invoke();
			}
		}
	}

	public String getSessionName() {
		return sessionName;
	}

	public void setSessionName(String sessionName) {
		this.sessionName = sessionName;
	}

	public String getExcludeName() {
		return excludeName;
	}

	public void setExcludeName(String excludeName) {
		this.excludeName = excludeName;
	}

	public List<String> getList() {
		return excludeActionList;
	}

	public void setList(List<String> list) {
		this.excludeActionList = list;
	}
}
